﻿using Furion;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using System;
using System.Text.Json;

namespace CN.T.Backend.Web.Core
{
    public class Startup : AppStartup
    {
        public void ConfigureServices(IServiceCollection services)
        {
            services.AddConsoleFormatter();
            services.AddJwt<JwtHandler>();
            //services.AddSession();

            services.AddDistributedMemoryCache();//启用内存缓存
            services.AddSession(options =>
            {
                options.IdleTimeout = TimeSpan.FromMinutes(10);//设置session过期时间
                options.Cookie.IsEssential = true;
            });
            //跨域
            services.AddCors(policy =>
            {
                policy.AddPolicy("CorsPolicy", opt => opt
                .AllowAnyOrigin()
                .AllowAnyHeader()
                .AllowAnyMethod()
                .WithExposedHeaders("X-Pagination"));
            });

            // 注册内存缓存

            services.AddSingleton<IMemoryCache>(new MemoryCache(new MemoryCacheOptions()));
            
            services.AddUnifyJsonOptions("special", new JsonSerializerOptions // 如果使用 Newtonsoft.Json => new JsonSerializerSettings
            {
                PropertyNamingPolicy = null
            });
            services.AddCorsAccessor();

            services.AddControllers().AddInjectWithUnifyResult<YourRESTfulResultProvider>();

        }

        public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
        {
            if (env.IsDevelopment())
            {
                app.UseDeveloperExceptionPage();
            }

            app.UseHttpsRedirection();
            app.UseSession();
            app.UseCors("CorsPolicy");//支持跨域
            app.UseRouting();

            app.UseCorsAccessor();

            app.UseAuthentication();
            app.UseAuthorization();

            app.UseInject(string.Empty);

            app.UseEndpoints(endpoints =>
            {
                endpoints.MapControllers();
            });
            
            app.UseStaticFiles();
        }
    }
}